<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class AttributeController extends Controller
{
    public function getIndex()
    {
        $category = DB::table('ym_category')->where('pid',0)->get();
        return view('/admin/Attribute',['category'=>$category]);
    }

    //修改商品属性
    public function getEdit($id,$name)
    {
        $attr = DB::table('ym_product_attr')->where('category_id',$id)->get();
        return view('/admin/Attributeedit',['attr'=>$attr,'categoryname'=>$name,'id'=>$id]);
    }
    //保存修改的属性
    public function getSave(Request $request)
    {
        //属性id
         $id = $request->input('id');
         $attrname = $request->input('attrname');
         $category_id = $request->input('category_id');
         //修改属性表
         DB::table('ym_product_attr')->where('id',$id)->update(['name'=>$attrname]);
         //修改属性表的值
         //原始属性
         $original = $request->input('originalattr');
         $res = DB::update("update ym_attribute_val set attr_name = '{$attrname}' 
            where category_id={$category_id} and attr_name='{$original}'");
         if($res){
            echo 1;
         }else{
            echo 0;
         }
    }

    //添加商品属性
    public function getAdd($id,$name)
    {
      return view('/admin/Attributeadd',['id'=>$id,'categoryname'=>$name]); 
    }
    //插入商品属性
    public function postInsert(Request $request)
    {
        //新添加的属性名称
        $attr = $request->except(['_token','category_id']);
        //商品分类id
        $id = $request->input('category_id');
        foreach($attr as $k=>$v){
                $arr['name'] = $v;
                $arr['category_id'] = $id;
                $res = DB::table('ym_product_attr')->insert($arr);
        }  
        //添加成功
        if($res){
            return redirect('/admin/attribute')->with('success','属性添加成功');
        }else{
            return back()->with('error','属性添加失败');
        }

    }

    //删除商品属性页面
    public function getShowdel($id,$name)
    { 
        //商品分类id
        $attr = DB::table('ym_product_attr')->where('category_id',$id)->get();
        return view('/admin/Attributeshowdel',['attr'=>$attr,'categoryname'=>$name,'id'=>$id]);
    }

    //ajax删除属性
    public function getDel(Request $request)
    {
        //属性id
         $id = $request->input('id');
         $attrname = $request->input('attrname');
         $category_id = $request->input('category_id');
         //删除属性
         DB::table('ym_product_attr')->where('id',$id)->delete();
         //删除属性表的属性值
         $res = DB::delete("update ym_attribute_val set attr_name = '{$attrname}' 
            where category_id={$category_id} and attr_name='{$attrname}'");
         if($res){
            echo 1;
         }else{
            echo 0;
         }
    }
}
